/**************************************************************************************
*
*	Copyright (C) 2010 - 2012 Brent Andrew O. Chua - See LICENSE.txt for more info.
*		
*	Filename	-	ResourcePoolItem.cpp
*
*	Comments	-	See ResourcePoolItem.h
*
**************************************************************************************/

#include "../Include/ResourcePoolItem.h"
#include "../Include/ResourcePool.h"
#include "../Include/AsyncLoadResource.h"
#include "../Include/Engine.h"

namespace Pulse
{
	IResourcePoolItem::IResourcePoolItem( void )
		: /*RefCounter( 1 ),*/ m_pResPool(NULL), m_hRes(0), m_resFlags(0)
	{

	}

	const String * IResourcePoolItem::GetResourceName( void ) const
	{
		if ( m_pResPool )
			return m_pResPool->FindResourceName( m_hRes );

		return NULL;
	}

	void IResourcePoolItem::SetResourceName( const CHAR *pName )
	{
		if ( m_pResPool )
			return m_pResPool->SetResourceName( m_hRes, pName );
	}

	INT IResourcePoolItem::Release( void )
	{

		INT refCount = RefCounter::Release();
		if ( refCount == 0 )
		{
			//m_pResPool->AcquireLock();
			m_pResPool->DestroyResource( this );
			//m_pResPool->ReleaseLock();
		}

		return refCount;
	}

	EErrorCode::Type IResourcePoolItem::PerformInitialize( BOOL bASyncLoad )
	{
		if ( bASyncLoad )
		{
			m_asyncLoad.SetResourceToLoad( &m_adapterResLoader );
			Engine::GetInstance()->GetTaskScheduler()->AddTask( &m_asyncLoad );
			return EErrorCode::OKAY;
		}
		else
		{
			if ( LoadResource() )
			{
				SetFlagCreated();
				return EErrorCode::OKAY;
			}

			SetFlagError();
			return EErrorCode::LOGIC;
		}
	}

	IResourcePoolItem::AdapterResPoolLoader::AdapterResPoolLoader( void )
		: m_pRes( PSX_NULL )
	{

	}

	IResourcePoolItem::AdapterResPoolLoader::~AdapterResPoolLoader( void )
	{
		PSX_SafeRelease( m_pRes );
	}

	void IResourcePoolItem::AdapterResPoolLoader::SetResourcePoolItem( IResourcePoolItem *pRes )
	{
		PSX_SafeRelease( m_pRes );

		m_pRes = pRes;

		if ( pRes )
			pRes->AddRef();
	}

	BOOL IResourcePoolItem::AdapterResPoolLoader::Run( TaskStatus *pTaskStatus ) 
	{
		if ( m_pRes->LoadResource() )
		{
			pTaskStatus->SetDone();

			return TRUE;
		}

		// Resource won't get deleted as long as there's still
		//	an object referencing it. We release it here so that
		//  if no other object is referencing this resource, this
		//	resource will get deleted.
		PSX_SafeRelease( m_pRes );

		return FALSE;
	}

}